package com.lagou.sqlsession;

import com.lagou.exceptions.PersistenceException;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor();
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) {
        try {
            MappedStatement mappedStatement = this.configuration.getMappedStatementMap().get(statementId);
            return executor.query(this.configuration, mappedStatement, params);
        } catch (Exception e) {
            throw new PersistenceException("错误查询数据库, statementId=" + statementId, e);
        }
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) {
        List<Object> objects;
        objects = this.selectList(statementId, params);
        if (objects == null || objects.isEmpty()) {
            return null;
        } else if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new PersistenceException("结果不唯一, statementId=" + statementId);
        }
    }

    @Override
    public int insert(String statementId, Object... params) {
        return this.update(statementId, params);
    }

    @Override
    public int update(String statementId, Object... params) {
        try {
            MappedStatement ms = configuration.getMappedStatementMap().get(statementId);
            return executor.update(configuration, ms, params);
        } catch (Exception e) {
            throw new PersistenceException("执行失败, statementId=" + statementId, e);
        }
    }

    @Override
    public int delete(String statementId, Object... params) {
        return this.update(statementId, params);
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        return this.configuration.getMapper(type, this);
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }

}
